package com.cjl.jvm.gc;

/**
 *  一个对象的finalize 方法最多只会被系统调用一次
 *  由来：早期便于C++  析构转变
 *  现状：不推荐，不确定性高   不如try finally
 */
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive(){
        System.out.println("FinalizeEscapeGC.isAlive");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("FinalizeEscapeGC.finalize");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();

        SAVE_HOOK = null;
        System.gc();

        Thread.sleep(500);

        if (SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else {
            System.out.println("FinalizeEscapeGC.main is dead");
        }


        System.out.println("FinalizeEscapeGC.main-------------");

        SAVE_HOOK = null;
        System.gc();

        Thread.sleep(500);

        if (SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else {
            System.out.println("FinalizeEscapeGC.main is dead");
        }
    }
}
